<?php

class AuthenticateController extends Zend_Controller_Action
{

	public function indexAction()
	{
		if (Zend_Auth::getInstance()->hasIdentity()) {
			$this->_redirect('/');
		} else {
			$this->_redirect('authenticate/login');
		}

	}

	public function loginAction()
	{
		$request = $this->getRequest();
		 
		//Disable Layout to just show login screen without Navigation, Header etc.
		$this->_helper->layout()->disableLayout();
		 
		$form = new Application_Form_AuthenticationLogin();
		 
		if($request->isPost()) {
			if($form->isValid($this->_request->getPost()))
			{
				$authAdapter = $this->getAuthAdapter();

					
				$user = $form->getValue('username');
				$pass = $form->getValue('password');
					
				$authAdapter->setIdentity($user);
				$authAdapter->setCredential(md5($pass));
					
				$auth = Zend_Auth::getInstance();
				$result = $auth->authenticate($authAdapter);
				
					
				if($result->isValid())
				{
					$identity = $authAdapter->getResultRowObject(null, "password");

					$authStorage = $auth->getStorage();
					$authStorage->write($identity);
					
					$this->_redirect('authenticate/index');
				} else {
					$form->populate($this->_request->getPost());
					$this->view->errorMsg = "Login failed! Please try again.";
				}
			}
		}
		$this->view->form = $form;

	}

	public function logoutAction()
	{
		Zend_Auth::getInstance()->clearIdentity();
		$this->_redirect('authenticate/login');
	}

	private function getAuthAdapter()
	{
		$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());

		$authAdapter->setTableName('tbl_tool_user');
		$authAdapter->setIdentityColumn('username');
		$authAdapter->setCredentialColumn('password');
		 
		return $authAdapter;
	}

	public function denyAction()
	{
		$this->view->pageTitle = "Access denied";
	}


}



